package com.example.blesdk;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({"ShowToast", "HandlerLeak"})
public class MainActivity extends Activity implements OnClickListener {
    private Button bt_send;
    private EditText et_content;
    private EditText et_ble_names;
    private TextView tv_log;
    private MainActivity context;
    private BluetoothLeService mBluetoothLeService;
    private Button bt_confirm;
    private Button bt_clean;
    private TextView tv_status;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.STATE_SEARCHDEVICE:
                    String log = (String) msg.obj;
                    String[] logs = log.split(",");
                    tv_status.setText(logs[0]);
                    break;
                case Constant.STATE_DISCONNECTED:
                    String status_dis = (String) msg.obj;
                    tv_status.setText(status_dis);
                    break;
                case Constant.STATE_CONNECTING:
                    String status_con = (String) msg.obj;
                    tv_status.setText(status_con);
                    break;
                case Constant.STATE_CONNECTED:
                    String status_connected = (String) msg.obj;
                    tv_status.setText(status_connected);
                    break;
                case Constant.STATE_DISCONNECTING:
                    String status_discon = (String) msg.obj;
                    tv_status.setText(status_discon);
                    break;
                case Constant.STATE_WRITEDATA:
                    String write_success = (String) msg.obj;
                    tv_status.setText(write_success);
                    break;
                case Constant.STATE_NOTIFY:
                    String status_notify = (String) msg.obj;
                    tv_status.setText(status_notify);
                    break;
                case Constant.STATE_EXTRADATA:
                    String status_extradata = (String) msg.obj;
                    Logutil.e("----data----" + status_extradata);
                    //处理数据
//                    status_extradata = extracted(status_extradata);
                    String lastText = tv_log.getText().toString();
                    tv_log.setText("");
                    tv_log.setText(lastText + "\n" + status_extradata);
                    break;
                case Constant.STATE_SEARCHING:
                    String status_searching = (String) msg.obj;
                    tv_status.setText(status_searching);
                    break;
                case Constant.STATE_SEARCHFAIL:
                    String status_searchFail = (String) msg.obj;
                    tv_status.setText(status_searchFail);
                    break;
                default:
                    break;
            }
        }
    };

    private Intent serviceIntent;
    private boolean isBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_main);

        initViews();
        initEvents();
        serviceIntent = new Intent(context, BluetoothLeService.class);
        isBound = bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
        Logutil.e("--------bindService----" + isBound);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, makeGattUpdateIntentFilter());
        if (context != null) {
            isBound = bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (serviceIntent != null) {
            stopService(serviceIntent);
            isBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_GATT_CONNECTED);
        intentFilter.addAction(Constant.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(Constant.ACTION_GATT_SERVICES_DISCOVERED);

        intentFilter.addAction(Constant.ACTION_GATT_DISCONNECTING);
        intentFilter.addAction(Constant.ACTION_GATT_CONNECTING);
        intentFilter.addAction(Constant.ACTION_DATA_EXTRA_DATA);
        intentFilter.addAction(Constant.SEARCH_DEVICE);
        intentFilter.addAction(Constant.WRITE_SUCCEED);
        intentFilter.addAction(Constant.ACTION_NOTIFY);
        intentFilter.addAction(Constant.ACTION_SEARCHING);
        intentFilter.addAction(Constant.ACTION_SEARCHFAIL);
        return intentFilter;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Message message = handler.obtainMessage();
            Logutil.e("----action---" + action);
            if (Constant.SEARCH_DEVICE.equals(action)) {
                String devices = intent.getStringExtra(Constant.SEARCH_DEVICE);
                message.what = Constant.STATE_SEARCHDEVICE;
                message.obj = devices;
                handler.sendMessage(message);
            } else if (Constant.ACTION_GATT_DISCONNECTED.equals(action)) {
                String status = intent.getStringExtra(Constant.ACTION_GATT_DISCONNECTED);
                message.what = Constant.STATE_DISCONNECTED;
                message.obj = status;
                handler.sendMessage(message);
            } else if (Constant.ACTION_GATT_CONNECTING.equals(action)) {
                String status = intent.getStringExtra(Constant.ACTION_GATT_CONNECTING);
                message.what = Constant.STATE_CONNECTING;
                message.obj = status;
                handler.sendMessage(message);
            } else if (Constant.ACTION_GATT_CONNECTED.equals(action)) {
                String status = intent.getStringExtra(Constant.ACTION_GATT_CONNECTED);
                message.what = Constant.STATE_CONNECTED;
                message.obj = status;
                handler.sendMessage(message);
            } else if (Constant.ACTION_GATT_DISCONNECTED.equals(action)) {
                String status = intent.getStringExtra(Constant.ACTION_GATT_DISCONNECTED);
                message.what = Constant.STATE_DISCONNECTED;
                message.obj = status;
                handler.sendMessage(message);
            } else if (Constant.ACTION_DATA_EXTRA_DATA.equals(action)) {
                String data = intent.getStringExtra(Constant.ACTION_DATA_EXTRA_DATA);
                message.what = Constant.STATE_EXTRADATA;
                message.obj = data;
                handler.sendMessage(message);
            } else if (Constant.WRITE_SUCCEED.equals(action)) {
                String data = intent.getStringExtra(Constant.WRITE_SUCCEED);
                message.what = Constant.STATE_WRITEDATA;
                message.obj = data;
                handler.sendMessage(message);
            } else if (Constant.ACTION_NOTIFY.equals(action)) {
                String data = intent.getStringExtra(Constant.ACTION_NOTIFY);
                message.what = Constant.STATE_NOTIFY;
                message.obj = data;
                handler.sendMessage(message);
            } else if (Constant.ACTION_SEARCHING.equals(action)) {
                String data = intent.getStringExtra(Constant.ACTION_SEARCHING);
                message.what = Constant.STATE_SEARCHING;
                message.obj = data;
                handler.sendMessage(message);
            } else if (Constant.ACTION_SEARCHFAIL.equals(action)) {
                String data = intent.getStringExtra(Constant.ACTION_SEARCHFAIL);
                message.what = Constant.STATE_SEARCHFAIL;
                message.obj = data;
                handler.sendMessage(message);
                Logutil.e("-------搜索失败------");
            }
        }
    };

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Logutil.e("------------init fail---------");
                finish();
            } else {
                Logutil.e("---------init success------------");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private void initEvents() {
        bt_send.setOnClickListener(context);
        bt_clean.setOnClickListener(context);
        bt_confirm.setOnClickListener(context);
    }

    private void initViews() {
        et_content = (EditText) findViewById(R.id.et_content);
        et_ble_names = (EditText) findViewById(R.id.et_ble_names);
        bt_send = (Button) findViewById(R.id.bt_send);
        tv_log = (TextView) findViewById(R.id.tv_log);
        bt_confirm = (Button) findViewById(R.id.bt_confirm);
        bt_clean = (Button) findViewById(R.id.btn_clean);
        tv_status = (TextView) findViewById(R.id.tv_status);
    }

    @SuppressLint({"NewApi", "ShowToast"})
    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.bt_send) {//测试 i359  033coffee01
			/*if(mBluetoothLeService!=null){
				mBluetoothLeService.sendLight(getConnectByte());
				return;
			}*/
            String content = et_content.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(context, "Please enter the data to be sent", Toast.LENGTH_SHORT).show();
                return;
            }
            if (mBluetoothLeService != null) {
                mBluetoothLeService.sendLight(Utils.hexStringToBytes(content));
            }

        } else if (i == R.id.bt_confirm) {
            String names = et_ble_names.getText().toString().trim();
            if (TextUtils.isEmpty(names)) {
                Toast.makeText(context, "Enter a ble name", Toast.LENGTH_SHORT).show();
                return;
            }
            if (mBluetoothLeService != null) {
                mBluetoothLeService.setName(names);
            }
            tv_status.setText("扫描中...");

        } else if (i == R.id.btn_clean) {
            tv_log.setText("");

        } else {
        }
    }

    //i359
    public static byte[] getConnectByte() {
        byte[] data = new byte[]{0x55, 0x0A, 0x02, (byte) 0xA6, 0x01, 0x00};
        data[5] = (byte) (data[0] + data[1] + data[2] + data[3] + data[4]);
        return data;
    }

    //ble fat
    private String extracted(String status_extradata) {
        // 体重数据处理
        int UnitWeightH = 0;  // 体重高字节
        int WeightL = 0;     // 体重低字节
        try {
            UnitWeightH = Integer.parseInt(status_extradata.substring(4, 6), 16);
            WeightL = Integer.parseInt(status_extradata.substring(6, 8), 16);
        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
        int weightH = (UnitWeightH & 0x3f) << 8;// 体重高字节
        float weightKg = (float) ((weightH + WeightL) / 10.0);
        Logutil.w("---显示体重数据---重量值------" + String.valueOf(weightKg) + "Kg");
        return weightKg + "Kg";
    }
}
